<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-11-05
 * Time: 16:37
 */

namespace App\Http\Controllers\Api\V1\Manager\Good;


use App\Exports\UniversalExport;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Expressfee;
use App\Models\Good;
use App\Models\GoodsOneType;
use App\Models\GoodsSpecOne;
use App\Models\GoodsSpecTwo;
use App\Models\GoodsStock;
use App\Models\GoodsTwoType;
use App\Models\IntegralGood;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Supplier;
use App\Models\UserHome;
use App\Models\UserStatistics;
use App\Models\VipLog;
use App\Services\Manager\GoodsService;
use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class IntegralGoodController extends Controller
{

    private $namespace = "App\Http\Controllers\Api\V1\Manager\Good\IntegralGoodController";

    public function index(Request $request)
    {
        $id = $request->id;
        $name = $request->name;
        $code = $request->code;
        $chandi = $request->chandi;
        $is_speciality = $request->is_speciality;
        $is_handpick = $request->is_handpick;
        $goods_one_type_id = $request->goods_one_type_id;
        $goods_two_type_id = $request->goods_two_type_id;
        $supplier_id = $request->supplier_id;
        $brand_id = $request->brand_id;
        $supplier_name = $request->supplier_name;
        $brand_name = $request->brand_name;
        $status = $request->status;
        $pageSize = $request->pageSize;
        $sql = IntegralGood::select('t1.id', 't1.status', 't1.brand', 't1.image', 't1.name', 't3.name as goods_one_type_name', 't4.name as goods_two_type_name', 't1.chandi', 't1.cost_price', 't1.pure_cost_price',
            't1.use_integral', 't1.sale_num', 't1.total_sale_num', 't5.suppname as supplier_name','t1.code','t1.shuilv')
            ->from((new IntegralGood())->getTable() . ' as t1')
            //->leftJoin((new Brand())->getTable() . ' as t2', 't1.brand_id', '=', 't2.id')
            ->leftJoin((new GoodsOneType())->getTable() . ' as t3', 't1.goods_one_type_id', '=', 't3.id')
            ->leftJoin((new GoodsTwoType())->getTable() . ' as t4', 't1.goods_two_type_id', '=', 't4.id')
            ->leftJoin((new Supplier())->getTable() . ' as t5', 't1.supplier_id', '=', 't5.id')
            ->where('t1.is_del', 0);
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        if (isset($idList[0])) {
            $sql->whereIn('t1.id', $idList);
        }
        if (isset($supplier_name)) {
            $sql->where('t5.suppname', 'like', "%$supplier_name%");
        }
        if (isset($brand_name)) {
            $sql->where('t1.brand', 'like', "%$brand_name%");
        }
        if (isset($id)) {
            $sql->where('t1.id', $id);
        }
        if (isset($name)) {
            $sql->where('t1.name', 'like', "%$name%");
        }
        if (isset($code)) {
            $sql->where('t1.code', 'like', "%$code%");
        }
        if (isset($chandi)) {
            $sql->where('t1.chandi', 'like', "%$chandi%");
        }
        if (isset($is_speciality)) {
            $sql->where('t1.is_speciality', $is_speciality);
        }
        if (isset($is_handpick)) {
            $sql->where('t1.is_handpick', $is_handpick);
        }
        if (isset($goods_one_type_id)) {
            $sql->where('t1.goods_one_type_id', $goods_one_type_id);
        }
        if (isset($goods_two_type_id)) {
            $sql->where('t1.goods_two_type_id', $goods_two_type_id);
        }
        if (isset($supplier_id)) {
            $sql->where('t1.supplier_id', $supplier_id);
        }
        if (isset($brand_id)) {
            $sql->where('t1.brand_id', $brand_id);
        }
        if (isset($status)) {
            if ($status == 30) {
                $sql->whereIn('t1.status', [30, 40]);
            } else {
                $sql->where('t1.status', $status);
            }
        }

        if (isset($request->excel)) {
            $goodList = $sql->orderByDesc('t1.createtime')
                ->get()
                ->toArray();
            $title = ['商品id','商品名称','商品编号','品牌','产地','税率','一级分类','二级分类','供应商名称','商品状态','销售积分','含税成本价','不含税成本价','月销量','总销量'];
            $data = [];
            $status = [1=>'上架',2=>'下架',30=>'每日爆款',40=>'限时秒杀'];
            $is_speciality = [0=>'不是',1=>'是'];
            foreach ($goodList as $value) {
                $goodDetail = [];
                $goodDetail[] = $value['id'];
                $goodDetail[] = $value['name'];
                $goodDetail[] = $value['code'];
                $goodDetail[] = $value['brand'];
                $goodDetail[] = $value['chandi'];
                $goodDetail[] = $value['shuilv'];
                $goodDetail[] = $value['goods_one_type_name'];
                $goodDetail[] = $value['goods_two_type_name'];
                $goodDetail[] = $value['supplier_name'];
                $goodDetail[] = $status[$value['status']];
                $goodDetail[] = $value['use_integral'];
                $goodDetail[] = $value['cost_price'];
                $goodDetail[] = $value['pure_cost_price'];
                $goodDetail[] = $value['sale_num'];
                if (!isset($value['total_sale_num'])) {
                    $value['total_sale_num'] = 0;
                }
                $goodDetail[] = $value['total_sale_num'];
                $data[] = $goodDetail;
            }
            return Excel::download(new UniversalExport($data, $title), "大转盘中奖明细" . date("ymdHis") . '.xlsx');
        }
        $goodList = $sql->orderByDesc('t1.createtime')
            ->paginate($pageSize)
            ->toArray();
        $data['goodsList'] = $goodList['data'];
        foreach ($data['goodsList'] as $key => $value) {
            if (!isset($data['goodsList'][$key]['total_sale_num'])) {
                $data['goodsList'][$key]['total_sale_num'] = 0;
            }
            $data['goodsList'][$key]['image'] = path($value['image']);
        }
        $data['totalNum'] = $goodList['total'];
        return $this->apiResponse($data);
    }

    public function show(Request $request, $id)
    {
        $good = IntegralGood::select('t1.id', 't1.status', 't1.name', 't1.code', 't1.brand_id', 't1.brand', 't1.chandi', 't1.shuilv', 't1.goods_one_type_id', 't3.name as goods_one_type_name', 't1.goods_two_type_id',
            't4.name as goods_two_type_name', 't1.supplier_id', 't5.suppname', 't1.expressfee_id', 't6.name as expressfee_name', 't1.is_speciality', 't1.is_handpick', 't1.is_overside', 't1.province_id',
            't1.province', 't1.city_id', 't1.city', 't1.image', 't1.images', 't1.introduce', 't1.content', 't1.zhongliang')
            ->from((new IntegralGood())->getTable() . ' as t1')
            ->leftJoin((new Brand())->getTable() . ' as t2', 't1.brand_id', '=', 't2.id')
            ->leftJoin((new GoodsOneType())->getTable() . ' as t3', 't1.goods_one_type_id', '=', 't3.id')
            ->leftJoin((new GoodsTwoType())->getTable() . ' as t4', 't1.goods_two_type_id', '=', 't4.id')
            ->leftJoin((new Supplier())->getTable() . ' as t5', 't1.supplier_id', '=', 't5.id')
            ->leftJoin((new Expressfee())->getTable() . ' as t6', 't1.expressfee_id', '=', 't6.id')
            ->where('t1.id', $id)
            ->where('t1.is_del', 0)
            ->first();
        if ($good) {
            $good['image'] = path($good['image']);
            if (isset($good['images']) && !empty($good['images'])) {
                $images = explode(',', $good['images']);
                $imagess = array();
                foreach ($images as $v) {
                    $imagess[] = path($v);
                }
                $good['images'] = $imagess;
            } else {
                $good['images'] = [];
            }
            $good['goods_spec_one'] = GoodsSpecOne::where('goods_integral_id', $id)->get()->toArray();
            $good['goods_spec_two'] = GoodsSpecTwo::where('goods_integral_id', $id)->get()->toArray();
        }
        return $this->apiResponse($good);
    }

    public function store(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        $data = $request->only('name', 'code', 'brand', 'chandi', 'shuilv', 'goods_one_type_id', 'goods_two_type_id', 'supplier_id',
            'expressfee_id', 'is_speciality', 'is_handpick', 'is_overside', 'province_id',
            'province', 'city_id', 'city', 'image', 'images', 'introduce', 'content', 'zhongliang');
        $goods_spec_one = $request->goods_spec_one;
        $goods_spec_two = $request->goods_spec_two;

        if (!isset($data['name']) || !isset($data['code']) || !isset($data['brand']) || !isset($data['chandi']) || !isset($data['shuilv'])||
            !isset($data['supplier_id']) || !isset($data['is_speciality']) || !isset($data['is_handpick']) ||
            !isset($data['is_overside']) || !isset($data['image']) || !isset($data['images'])) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        $images = null;
        foreach ($data['images'] as $value) {
            if (isset($images)) {
                $images .= "," . $value;
            } else {
                $images = $value;
            }
        }
        $data['images'] = $images;
        $data['author_id'] = $request->ADMINID;
        $data['updatetime'] = time();
        try {
            \DB::beginTransaction();
            if ($id) {
                //修改
                $good = IntegralGood::where('id', $id)->first();
                if (!isset($good) || ($good['status'] != 2) || $good['is_del']) {
                    return $this->apiResponse('', config('errorLiu.SHANGPINFBINGFEIXIAJIAZHUANGT'));
                }
                $content = "修改";
                IntegralGood::where('id', $id)->update($data);
            } else {
                //新增
                $content = "新增";
                $data['createtime'] = time();
                $id = IntegralGood::insertGetId($data);
            }
            if (isset($goods_spec_one[0])) {
                $goodsSpecOneId = [];
                $goodsSpecTwoId = [];
                $goodsStock = [];
                $i = 0;
                if (isset($goods_spec_two[0])) {
                    foreach ($goods_spec_one as $value) {
                        if (!$value['id']) {
                            $value['goods_integral_id'] = $id;
                            $value['id'] = GoodsSpecOne::insertGetId($value);
                        }
                        $goodsSpecOneId[] = $value['id'];
                        foreach ($goods_spec_two as $key => $val) {
                            if (!$val['id']) {
                                $val['goods_integral_id'] = $id;
                                $val['id'] = GoodsSpecTwo::insertGetId($val);
                                $goods_spec_two[$key]['id'] = $val['id'];
                            }
                            $goodsSpecTwoId[] = $val['id'];
                            $goodsStock[$i]['goods_integral_id'] = $id;
                            $goodsStock[$i]['goods_spec_one_id'] = $value['id'];
                            $goodsStock[$i]['goods_spec_two_id'] = $val['id'];
                            $i++;
                        }
                    }
                } else {
                    foreach ($goods_spec_one as $value) {
                        if (!$value['id']) {
                            $value['goods_integral_id'] = $id;
                            $value['id'] = GoodsSpecOne::insertGetId($value);
                        }
                        $goodsSpecOneId[] = $value['id'];
                        $goodsStock[$i]['goods_integral_id'] = $id;
                        $goodsStock[$i]['goods_spec_one_id'] = $value['id'];
                        $goodsStock[$i]['goods_spec_two_id'] = null;
                        $i++;
                    }
                }
                GoodsSpecOne::where('goods_integral_id', $id)->whereNotIn('id', $goodsSpecOneId)->delete();
                GoodsSpecTwo::where('goods_integral_id', $id)->whereNotIn('id', $goodsSpecTwoId)->delete();
                $goodsStockList = GoodsStock::where('goods_integral_id', $id)->get()->toArray();
                unset($value);
                unset($val);
                $goodsStockId = [];
                $goodsStockInsertList = [];
                $i = 0;
                foreach ($goodsStock as $value) {
                    $next = 0;
                    foreach ($goodsStockList as $val) {
                        if (($value['goods_integral_id'] == $val['goods_integral_id']) && ($value['goods_spec_one_id'] == $val['goods_spec_one_id']) && ($value['goods_spec_two_id'] == $val['goods_spec_two_id'])) {
                            $next = 1;
                            $goodsStockId[] = $val['id'];
                            break;
                        }
                    }
                    if ($next) {
                        continue;
                    }
                    $goodsStockInsertList[$i]['goods_integral_id'] = $value['goods_integral_id'];
                    $goodsStockInsertList[$i]['goods_spec_one_id'] = $value['goods_spec_one_id'];
                    $goodsStockInsertList[$i]['goods_spec_two_id'] = $value['goods_spec_two_id'];
                    //$goodsStockInsertList[$i]['image'] = $data['image'];
                    $i++;
                }
                GoodsStock::where('goods_integral_id', $id)->whereNotIn('id', $goodsStockId)->delete();
                GoodsStock::insert($goodsStockInsertList);
                $littleGoodsStock = null;
                $goodsStockList = GoodsStock::where('goods_integral_id', $id)->get()->toArray();
                unset($value);
                foreach ($goodsStockList as $value) {
                    if (isset($littleGoodsStock)) {
                        if (($value['use_integral'] > 0) && ($value['use_integral'] < $littleGoodsStock['use_integral'])) {
                            $littleGoodsStock = $value;
                        }
                    } else {
                        $littleGoodsStock = $value;
                    }
                }
                if (isset($littleGoodsStock)) {
                    IntegralGood::where('id', $id)->update([
                        'cost_price' => $littleGoodsStock['cost_price'],
                        'pure_cost_price' => $littleGoodsStock['pure_cost_price'],
                        'use_integral' => $littleGoodsStock['use_integral'],
                        'zhongliang' => $littleGoodsStock['zhongliang']
                    ]);
                }
            } else {
                GoodsSpecOne::where('goods_integral_id', $id)->delete();
                GoodsSpecTwo::where('goods_integral_id', $id)->delete();
                GoodsStock::where('goods_integral_id', $id)->delete();
            }
            //添加管理员日志开始
            $url = $this->namespace . "/store";
            $title = $content;
            $content .= "了id为【".$id."】的积分商品,内容为【".json_encode($data)."】";
            $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
            //添加管理员日志结束
            \DB::commit();
            return $this->apiResponse($id);
        } catch (\Exception $e) {
            \DB::rollback();
            return $this->apiResponse('', config('errorLiu.CAAOZUOSHIBAI'));
        }
    }

    public function destroy(Request $request, $id)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $good = IntegralGood::where('id', $id)->first();
        if ($good) {
            IntegralGood::where('id', $id)
                ->where('status', 2)
                ->update([
                    'status' => 2,
                    'is_del' => 1,
                    'old_status' => $good['status']
                ]);
            //添加管理员日志开始
            $url = $this->namespace . "/destroy";
            $title = "删除";
            $content = "删除了id为【".$id."】的积分商品";
            $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
            //添加管理员日志结束
        }
        return $this->apiResponse(true);
    }

    public function update(Request $request, $id)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $good = IntegralGood::where('id', $id)->first();
        if ($good) {
            if (!$good['is_del']) {
                if ($good['status'] != 2) {
                    IntegralGood::where('id', $id)->update([
                        'status' => 2
                    ]);
                    $content = "下架";
                } else {
                    $goodService = new GoodsService();
                    $res = $goodService->verify($good, $id, 1);
                    if ($res == -1) {
                        return $this->apiResponse('', config('errorLiu.GONGYINGSHANGYITINGZHIHEZ'));
                    }
                    if ($res == -2) {
                        return $this->apiResponse('', config('errorLiu.GASHANGPINXUANCZEZHONGLIANL'));
                    }
                    if ($res == -3) {
                        return $this->apiResponse('', config('errorLiu.GAISHANGPINZANWUGUIGE'));
                    }
                    if ($res == -4) {
                        return $this->apiResponse('', config('errorLiu.GAISHANGPGUIGESEWEIWZ'));
                    }
                    if ($res == -5) {
                        return $this->apiResponse('', config('errorLiu.SHANGPINGUIGEZANWUTUPIANQING'));
                    }
                    if ($res == -6) {
                        return $this->apiResponse('', config('errorLiu.SHANGPINGWEITIANXIEHANSUIHUIBUHAN'));
                    }
                    IntegralGood::where('id', $id)->update([
                        'status' => 1
                    ]);
                    $content = "上架";
                }
                //添加管理员日志开始
                $url = $this->namespace . "/update";
                $title = "修改";
                $content .= "了id为【".$id."】的积分商品";
                $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
                //添加管理员日志结束
            }
        }
        return $this->apiResponse(true);
    }

    public function transfer(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $ids = $request->ids;
        $data = $request->only('goods_one_type_id', 'goods_two_type_id');
        if (!isset($data['goods_one_type_id']) || !isset($data['goods_two_type_id'])) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        IntegralGood::whereIn('id', $idList)->update([
            'goods_one_type_id' => $data['goods_one_type_id'],
            'goods_two_type_id' => $data['goods_two_type_id']
        ]);
        //添加管理员日志开始
        $url = $this->namespace . "/transfer";
        $title = "修改";
        $content = "批量修改了id包括【".json_encode($ids)."】的积分商品的分类";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }


    public function stock(Request $request)
    {
        $id = $request->id;
        $goodStockList = GoodsStock::select('t1.*', 't2.name as goods_spec_one_name', 't3.name as goods_spec_two_name')
            ->from((new GoodsStock())->getTable() . ' as t1')
            ->leftJoin((new GoodsSpecOne())->getTable() . ' as t2', 't1.goods_spec_one_id', '=', 't2.id')
            ->leftJoin((new GoodsSpecTwo())->getTable() . ' as t3', 't1.goods_spec_two_id', '=', 't3.id')
            ->where('t1.goods_integral_id', $id)
            ->orderByDesc('t1.id')
            ->get()
            ->toArray();
        $data['goodsStockList'] = $goodStockList;
        foreach ($data['goodsStockList'] as $key => $value) {
        }
        $data['totalNum'] = count($goodStockList);
        return $this->apiResponse($data);
    }

    public function stockStore(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        $data = $request->only('num', 'price', 'vip_price', 'pure_cost_price', 'cost_price', 'use_integral', 'image', 'zhongliang');
        if (!isset($data['num']) || !isset($data['use_integral']) || !isset($data['pure_cost_price'])
            || !isset($data['cost_price']) || !isset($data['use_integral']) || !isset($data['image'])) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        $goodsStock = GoodsStock::where('id', $id)->first();
        if ($goodsStock) {
            $goodId = $goodsStock['goods_integral_id'];
            $good = IntegralGood::where('id', $goodId)->first();
            if (!isset($good) || ($good['status'] != 2) || $good['is_del']) {
                return $this->apiResponse('', config('errorLiu.SHANGPINFBINGFEIXIAJIAZHUANGT'));
            }
            GoodsStock::where('id', $id)->update($data);
            $littleGoodsStock = null;
            $goodsStockList = GoodsStock::where('goods_integral_id', $goodId)->get()->toArray();
            unset($value);
            foreach ($goodsStockList as $value) {
                if (isset($littleGoodsStock)) {
                    if (($value['use_integral'] > 0) && ($value['use_integral'] < $littleGoodsStock['use_integral'])) {
                        $littleGoodsStock = $value;
                    }
                } else {
                    $littleGoodsStock = $value;
                }
            }
            if (isset($littleGoodsStock)) {
                IntegralGood::where('id', $goodId)->update([
                    'price' => $littleGoodsStock['price'],
                    'cost_price' => $littleGoodsStock['cost_price'],
                    'pure_cost_price' => $littleGoodsStock['pure_cost_price'],
                    'use_integral' => $littleGoodsStock['use_integral'],
                    'zhongliang' => $littleGoodsStock['zhongliang']
                ]);
            }
            //添加管理员日志开始
            $url = $this->namespace . "/stockStore";
            $title = "修改";
            $content = "修改了id为【".$id."】的积分商品规格,内容为【".json_encode($data)."】";
            $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
            //添加管理员日志结束
        }
        return $this->apiResponse(true);
    }


    public function deleteMore(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        IntegralGood::whereIn('id', $idList)->where('status', 2)->update([
            'old_status' => \DB::raw('status'),
            'status' => 2,
            'is_del' => 1
        ]);
        //添加管理员日志开始
        $url = $this->namespace . "/deleteMore";
        $title = "删除";
        $content = "批量删除了id包括【".json_encode($ids)."】的积分商品";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function updateMore(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        IntegralGood::whereIn('id', $idList)->update([
            'status' => 2
        ]);
        //添加管理员日志开始
        $url = $this->namespace . "/updateMore";
        $title = "修改";
        $content = "批量下架了id包括【".json_encode($ids)."】的积分商品";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "积分商品模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }
}